package kr.saeildamil.androidforstudy2.ch2930;

import kr.saeildamil.androidforstudy2.R;
import kr.saeildamil.androidforstudy2.ch2930.LocalService.LocalBinder;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;

public class BoundServiceTest extends Activity implements OnClickListener{
	LocalService mService;
	boolean mBound;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ch29_boundservice);
		
		findViewById(R.id.ch29_bounderservice_callbtn).setOnClickListener(this);
	}

	@Override
	protected void onResume() {
		super.onResume();
		Intent intent = new Intent(this, LocalService.class);
		bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
	}
	
	
	
	@Override
	protected void onPause() {
		super.onPause();
		if (mBound) {
			unbindService(mConnection);
		}
	}



	ServiceConnection mConnection = new ServiceConnection() {
		
		@Override
		public void onServiceDisconnected(ComponentName name) {
			mBound = false;
		}
		
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			LocalBinder binder = (LocalBinder) service;
			mService = binder.getService();
			mBound = true;
		}
	};
	
	@Override
	public void onClick(View v) {
		if(mBound == true){
			Toast.makeText(this, Integer.toString(mService.getRandomNumber()), Toast.LENGTH_SHORT).show();
		}else{
			Toast.makeText(this, "Fail to connect", Toast.LENGTH_SHORT).show();
		}
	}
}
